# your_file.py
import os
import re
import shutil

from db_connector import connector
from file_utils import list_files ,calculate_md5,create_folder,get_pdf_page_count
from datetime import datetime
from dataclasses import dataclass
from pdf2image import convert_from_path
import fitz  # PyMuPDF

@dataclass
class CatalogBook:
    bookId: int
    shelfId: int
    title: str
    fileName: str
    filePath: str
    cover: str
    status: str
    delFlag: str
    fileId: str
    bookType: str
    pageCount: str
    createBy:str
    createTime:str
    updateBy:str
    updateTime:str
    remark:str

def initBook(folderPath,filename):
    book_id = extract_info_from_filename(filename)
    file_name_without_extension, file_extension = os.path.splitext(filename)
    yonghan = "《勇罕》"
    wenbang = "《文蚌》"
    file_id = "100" if yonghan in filename else "101"
    filenname = "/profile/upload/yonghan" if yonghan in filename else "/profile/upload/wenbang"
    catalog_book = CatalogBook(
        bookId=book_id,
        shelfId=file_id,
        title=file_name_without_extension,
        fileName=f"{filenname}/{filename}",
        filePath=f"{folderPath}\\{file_name}",
        cover="",
        status="1",
        delFlag="0",
        fileId="",
        bookType="0",
        pageCount="1",
        createBy='',
        createTime=datetime.now(),
        updateBy='',
        updateTime='',
        remark=''
    )
    return catalog_book

# 用于存储失败的文件名的数组
book_dicts = []



#根据文件明生成id
def extract_info_from_filename(filename):
    # 匹配年份和期数的正则表达式
    # pattern1 = re.compile(r'《([^》]+)》(\d{4})年第(\d+)\S+(\d+)期')
    # match = re.search(r'(\d{4})年(?:第)?(\d+[-—]?\d*)[期总]*', text)
    filename = filename.replace(' ', '')
    pattern1 = re.compile(r'《(文蚌|勇罕)》(\d{4})年(?:第)?(\d+)\S+(\d+)期')
    pattern2 = re.compile(r'《(文蚌|勇罕)》(\d{4})年(?:第)?(\d+)期')

    
    # 使用正则表达式进行匹配
    match1 = pattern1.match(filename)
    match2 = pattern2.match(filename)

    if match1:
        # 获取年份和期数的匹配组
        shelf =  match1.group(1)
        shelfId = "00" if shelf == "勇罕" else "01"
        year = match1.group(2)
        issue_start = match1.group(3)
        issue_end = match1.group(4)
        return year+shelfId+issue_start
    elif match2:
        shelf =  match2.group(1)
        shelfId = "00" if shelf == "勇罕" else "01"
        # 获取年份和期数的匹配组
        year = match2.group(2)
        issue = match2.group(3)

        return year+shelfId+issue
    else:
        return None

def addBook(book):
    po = queryBook(book.bookId)
    if po:
        book.remark ="已存在！"
    else:
        # 进行插入数据
        re = insertBook(book)
        book.remark=f"新增数据{re}"

def upload(book):
    po = queryBook(book.bookId)
    if po:
        re = uploadBook(book)
        book.remark =f"更新数据:{re}"
    else:
        # 进行插入数据
        re = insertBook(book)
        book.remark=f"新增数据:{re}"

def insertBook(book):
    current_datetime = datetime.now()
    sql = (
        f"INSERT INTO `dh-wy-catalog`.`catalog_book` "
        f"(`book_id`, `title`, `fileName`, `cover`, `page_count`, `shelf_id`, "
        f"`file_id`, `book_type`, `status`, `del_flag`, `create_by`, "
        f"`create_time`, `update_by`, `remark`) "
        f"VALUES ('{book.bookId}', '{book.title}', "
        f"'{book.fileName}', '{book.cover}', '{book.pageCount}', '{book.shelfId}', '{book.bookId}', '0', '0', '0', "
        f"'', '{current_datetime}', '', '')"
    )
    print(sql)
    result = connector.execute(sql)
    print(result)
    return result

def uploadBook(book):
    current_datetime = datetime.now()
    sql = (
        f"UPDATE `dh-wy-catalog`.`catalog_book`"
        f"SET "
        f"`title` = '{book.title}', "
        f"`fileName` = '{book.fileName}', "
        f"`cover` = '{book.cover}',"
        f"`page_count` = '{book.pageCount}', "
        f"`shelf_id` = '{book.shelfId}',"
        f"`file_id` = '{book.bookId}',"
        f"`book_type` = '{book.bookType}',"
        f"`status` = '{book.status}',"
        f"`del_flag` = '{book.delFlag}',"
        f"`update_time` = '{current_datetime}'"
        f"WHERE `book_id` = '{book.bookId}'"
    )
    print(sql)
    result = connector.execute(sql)
    return result

def queryBook(book_id):
    sql = f"SELECT * FROM catalog_book WHERE book_id = '{book_id}'"
    result = connector.execute_query(sql)
    return result

import PyPDF2

def get_pdf_page_count(pdf_path):
    with open(pdf_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        page_count = len(pdf_reader.pages)
    return page_count

def get_pdf_page_count2(pdf_path):
    try:
        doc = fitz.open(pdf_path)
        page_count = doc.page_count
        return page_count
    except Exception as e:
        print(f"Error while getting PDF page count: {e}")
        return 0
    finally:
        doc.close()

def pdf_to_images(pdf_path,output_folder,file_name):
    temp = f"{output_folder}\\{file_name}\\temp"
    iamge = f"{output_folder}\\{file_name}\\image"
    if not os.path.exists(temp) or not os.path.isdir(temp):
        os.makedirs(temp)

    if not os.path.exists(iamge) or not os.path.isdir(iamge):
        os.makedirs(iamge)

    try:
        images = convert_from_path(pdf_path, output_folder=temp, poppler_path=r'E:\poppler-23.11.0\Library\bin',dpi=150)  # 替换成你的Poppler路径
        for i, image in enumerate(images):
            image_path = f"{iamge}\page{i + 1}.png"
            image.save(image_path, 'PNG')
            print(f"Page {i + 1} saved as {image_path}")
            book_dict = {}
        return book_dict
    except Exception as e:
        sys.stderr.write(str(e))

def is_pdf_by_extension(file_path):
    # 获取文件扩展名并转换为小写
    file_extension = file_path.split('.')[-1].lower()
    
    # 判断是否为PDF文件
    return file_extension == 'pdf'

# 移动文件
def move_file_to_completed_folder(pdf_path, completed_folder):
    # 获取文件名
    file_name = os.path.basename(pdf_path)

    # 构建目标文件路径
    destination_path = os.path.join(completed_folder, file_name)

    # 移动文件到已完成文件夹
    shutil.move(pdf_path, destination_path)
    print(f"文件 '{file_name}' 已移动到已完成文件夹。")

# 删除 tem文件夹
def delete_directory(directory_path):
    try:
        # 递归删除目录及其内容
        shutil.rmtree(directory_path)
        print(f"目录 '{directory_path}' 已成功删除。")
    except OSError as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    #  获取文件明
    wenbang = r"D:\Users\65720\Desktop\电信项目-方案\文艺\factory"
    yonghan = r"D:\Users\65720\Desktop\电信项目-方案\文艺\factory-2"
    test = r"D:\Users\65720\Desktop\电信项目-方案\文艺\factory-3"
    
    output_wengabng = r"D:\Users\65720\Desktop\电信项目-方案\文艺\product-3"
    output_yonghan = r"D:\Users\65720\Desktop\电信项目-方案\文艺\product-2"

    file_path = wenbang
    output_folder = output_wengabng
    file_names = list_files(file_path)

    for file_name in file_names:       
        catalog_book = initBook(file_path,file_name)
        print(catalog_book)
        # 获取页数
        catalog_book.pageCount = get_pdf_page_count2(catalog_book.filePath)
        # 封面
        catalog_book.cover = f"/profile/upload/book/{catalog_book.bookId}/image/page1.png"
        # 插入数据,更新数据
        upload(catalog_book)
        # 切图
        pdf_to_images(catalog_book.filePath, output_folder,catalog_book.bookId)

        # 移动文件
        move_file_to_completed_folder(catalog_book.filePath,f"{file_path}\\Completed")
        # 删除temp
        delete_directory(f"{output_folder}\\{catalog_book.bookId}\\temp")

        print(catalog_book)
        book_dicts.append(catalog_book)


    # connector.disconnect()
    # for book in book_dicts:
    #     print(book)
  